package com.qsmx.store.app.main.goods;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.Window;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qsmx.store.app.R;
import com.qsmx.store.app.R2;
import com.qsmx.store.app.entity.suit.SuitDetailEntity;
import com.qsmx.store.app.fustion.FustionManager;
import com.qsmx.store.app.fustion.FustionTag;
import com.qsmx.store.app.http.HttpHelper;
import com.qsmx.store.app.http.HttpUrl;
import com.qsmx.store.app.main.goods.adapter.GoodsCreateAdapter;
import com.qsmx.store.app.main.goods.adapter.GoodsListAdapter;
import com.qsmx.store.app.main.goods.entity.GoodsCreateOrderEntity;
import com.qsmx.store.app.main.goods.entity.GoodsEntity;
import com.qsmx.store.app.main.suit.entity.AuthorizeRecord;
import com.qsmx.store.app.util.CountDownTimerUtil;
import com.qsmx.store.app.util.DisplayUtil;
import com.qsmx.store.app.util.StringUtil;
import com.qsmx.store.app.widget.MyDialog;
import com.qsmx.store.core.delegates.AtmosDelegate;
import com.qsmx.store.core.event.QrScanEvent;
import com.qsmx.store.core.fusion.FusionCode;
import com.qsmx.store.core.fusion.FusionString;
import com.qsmx.store.core.net.callback.IError;
import com.qsmx.store.core.net.callback.IFailure;
import com.qsmx.store.core.net.callback.ISuccess;
import com.qsmx.store.core.util.dimen.DimenUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.WeakHashMap;

import butterknife.BindView;
import butterknife.OnClick;

public class GoodsSaleListDelegate extends AtmosDelegate {

    private List<GoodsCreateOrderEntity> mCreateGoodsList;
    private List<GoodsEntity> mGoodsData;
    private int allMoney;
    private String mCurrentBillNo;
    private MyDialog mPayStatusDialog = null;
    private CountDownTimerUtil timer;

    GoodsListAdapter mAdapter;
    GoodsCreateAdapter mCreateAdapter;

    @BindView(R2.id.rlv_goods)
    RecyclerView rlvGoods;
    @BindView(R2.id.rlv_create_order)
    RecyclerView rlvCreateOrder;
    @BindView(R2.id.tv_all_money)
    AppCompatTextView tvAllMoney;
    @BindView(R2.id.tv_want_pay_money)
    AppCompatTextView tvWantPayMoney;

    @OnClick(R2.id.tv_cash_pay)
    void onCashPay() {
        showCashPayDialog();
    }

    @OnClick(R2.id.tv_qr_pay)
    void onQrPay() {
        commitOrder("2");
        showPayStatusDialog(FustionTag.PAY_STATUS.WAIT_PAY);
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_goods_sale_list;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {

        initRecycler();
        initGoodsData();
    }

    private void initRecycler() {

        mCreateGoodsList = new ArrayList<>();
        mAdapter = new GoodsListAdapter(getContext());
        mCreateAdapter = new GoodsCreateAdapter(getContext());
        LinearLayoutManager createManager = new LinearLayoutManager(getContext());
        GridLayoutManager manager = new GridLayoutManager(getContext(), 3);

        rlvGoods.setLayoutManager(manager);
        rlvGoods.setAdapter(mAdapter);

        rlvCreateOrder.setLayoutManager(createManager);
        rlvCreateOrder.setAdapter(mCreateAdapter);

        DisplayUtil.showPayGoodsDisplay(getContext());

        mAdapter.setonItemClickListener(new GoodsListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

                GoodsCreateOrderEntity data = new GoodsCreateOrderEntity();
                data.setDetailNum(1);
                data.setGoodsName(mGoodsData.get(position).getGoodsName());
                data.setGoodsCode(mGoodsData.get(position).getGoodsSku());
                data.setGoodsId(mGoodsData.get(position).getGoodId());
                data.setPrice(mGoodsData.get(position).getPrice());
                data.setMoney(mGoodsData.get(position).getPrice());

                if (mCreateGoodsList != null && mCreateGoodsList.size() > 0) {
                    if (mCreateGoodsList.contains(data)) {
                        for (GoodsCreateOrderEntity entity : mCreateGoodsList) {
                            if (entity.getGoodsId() == data.getGoodsId()) {
                                entity.setDetailNum(entity.getDetailNum() + 1);
                                entity.setMoney(entity.getDetailNum() * entity.getPrice());
                            }
                        }
                    } else {
                        mCreateGoodsList.add(data);
                    }
                } else {
                    mCreateGoodsList.add(data);
                }

                mCreateAdapter.setData(mCreateGoodsList);
                mCreateAdapter.notifyDataSetChanged();
                orderInfoRefresh();

            }
        });

        mCreateAdapter.setonItemClickListener(new GoodsCreateAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

            }

            @Override
            public void onItemMin(View view, int position) {
                if (mCreateGoodsList.get(position).getDetailNum() > 1) {
                    mCreateGoodsList.get(position).setDetailNum(mCreateGoodsList.get(position).getDetailNum() - 1);
                    mCreateGoodsList.get(position).setMoney(mCreateGoodsList.get(position).getDetailNum() * mCreateGoodsList.get(position).getPrice());
                    mCreateAdapter.notifyDataSetChanged();
                    orderInfoRefresh();
                }
            }

            @Override
            public void onItemPlus(View view, int position) {

                mCreateGoodsList.get(position).setDetailNum(mCreateGoodsList.get(position).getDetailNum() + 1);
                mCreateGoodsList.get(position).setMoney(mCreateGoodsList.get(position).getDetailNum() * mCreateGoodsList.get(position).getPrice());
                mCreateAdapter.notifyDataSetChanged();
                orderInfoRefresh();

            }

            @Override
            public void onItemDelete(View view, int position) {
                mCreateGoodsList.remove(mCreateGoodsList.get(position));
                mCreateAdapter.notifyDataSetChanged();
                orderInfoRefresh();

            }
        });

    }

    @SuppressLint("SetTextI18n")
    private void orderInfoRefresh() {

        allMoney = 0;
        for (GoodsCreateOrderEntity entity : mCreateGoodsList) {
            allMoney = allMoney + entity.getMoney();
        }

        tvAllMoney.setText("￥" + allMoney);
        tvWantPayMoney.setText("￥" + allMoney);
    }

    private void initGoodsData() {

        WeakHashMap<String, Object> params = new WeakHashMap<>();
        params.put("deptId", FustionManager.mLoginData.getUser().getUser().getDept().getId());
        params.put("storageType", "1");

        HttpHelper.RestClientGet(params, HttpUrl.GET_GOODS_SALE_INFO,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        Type type = new TypeToken<List<GoodsEntity>>() {
                        }.getType();
                        Gson gson = new Gson();
                        mGoodsData = gson.fromJson(response, type);
                        mAdapter.setData(mGoodsData);
                        mAdapter.notifyDataSetChanged();

                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {

                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {

                    }
                });

    }

    private void showCashPayDialog() {
        final Dialog dialog = new Dialog(getContext(), R.style.dialog);
        dialog.setCancelable(true);
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.dialog_cash_pay);
        int width = (int) (DimenUtil.getScreenWidth() * 0.5);
        int height = (int) (DimenUtil.getScreenHeight() * 0.5);

        window.setLayout(width, height);

        AppCompatTextView tvSurePay = window.findViewById(R.id.tv_sure);
        tvSurePay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                commitOrder("1");
//                commitOrder(contentBean, mSuitNum, "1", mCoinOutType);
            }
        });

    }

    private void commitOrder(final String payMethod) {

//        AuthorizeRecord authorizeRecord = new AuthorizeRecord();
//        authorizeRecord.setAuthorizeId(1);
//
//        mAuthorizeRecordList.add(authorizeRecord);
        /**
         * deptId：门店ID
         * businessDate：营业日期
         * shift：班次
         * receivableMoney：应收金额
         * actualMoney：实收金额
         * changeMoney：找零金额
         * payMethod：支付方式   1-现金 2-微信 3-支付宝 4-扫码核销
         * payStatus：支付状态
         * memberId：会员ID
         * memberNo：会员编号
         * machineId：机台ID
         * machineCode：机台编号
         * remark：备注
         */
        JSONObject params = new JSONObject();
        params.put("deptId", FustionManager.mLoginData.getUser().getUser().getDept().getId());
        params.put("businessDate", FustionManager.mMachineData.getBusinessDate());
        params.put("shift", "1");
        params.put("payMethod", payMethod);
        params.put("payStatus", "");
//        if (mSearchMenInfo != null) {
//            params.put("memberId", mSearchMenInfo.getId());
//            params.put("memberNo", mSearchMenInfo.getMemberNo());
//        }
        params.put("receivableMoney", String.valueOf(allMoney));
        params.put("actualMoney", String.valueOf(allMoney));
        params.put("changeMoney", "0");
        params.put("authorizeRecordList", JSON.toJSON(new ArrayList<>()));
        params.put("machineId", FustionManager.mMachineData.getMachineId());
        params.put("machineCode", FustionManager.mMachineData.getMachineCode());
        params.put("remark", "");
        params.put("goodsSellDetails", JSON.toJSON(mCreateGoodsList));

        HttpHelper.RestClientPostRaw(params, HttpUrl.GOODS_SUBMIT,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        if (code == 201) {
                            mCurrentBillNo = response;
                            if (payMethod.equals("1")) {
                                initGoodsData();
                                mCreateGoodsList.clear();
                                tvAllMoney.setText("0");
                                tvWantPayMoney.setText("0");
                                mCreateAdapter.setData(mCreateGoodsList);
                                mCreateAdapter.notifyDataSetChanged();
                                showPayStatusDialog(FustionTag.PAY_STATUS.PAY_SUCCESS);
                            } else if (payMethod.equals("2")) {
                                FusionCode.SCAN_TYPE = FusionCode.QR_SCANNER;
                            }
                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {

                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {

                    }
                });

    }

    private void showPayStatusDialog(String status) {

        if (mPayStatusDialog == null) {
            mPayStatusDialog = new MyDialog(getContext(), R.style.dialog);
        }
        mPayStatusDialog.setCancelable(true);
        mPayStatusDialog.show();
        Window window = mPayStatusDialog.getWindow();
        window.setContentView(R.layout.dialog_pay_status);
        int width = (int) (DimenUtil.getScreenWidth() * 0.3);
        int height = (int) (DimenUtil.getScreenHeight() * 0.3);

        window.setLayout(width, height);

        AppCompatImageView ivPayStatusImg = window.findViewById(R.id.iv_status_img);
        AppCompatTextView tvPayStatusTip = window.findViewById(R.id.tv_pay_status_tips);
        AppCompatTextView tvWaitCoinOutTime = window.findViewById(R.id.tv_wait_coin_out_time);

        if (status.equals(FustionTag.PAY_STATUS.WAIT_PAY)) {
            Glide.with(getContext()).load(R.mipmap.icon_logo).into(ivPayStatusImg);
            tvPayStatusTip.setText(getString(R.string.suit_pay_wait));
            tvWaitCoinOutTime.setVisibility(View.GONE);
        } else if (status.equals(FustionTag.PAY_STATUS.PAYING)) {
            Glide.with(getContext()).load(R.mipmap.icon_logo).into(ivPayStatusImg);
            tvPayStatusTip.setText(getString(R.string.suit_paying));
            tvWaitCoinOutTime.setVisibility(View.GONE);
        } else if (status.equals(FustionTag.PAY_STATUS.PAY_SUCCESS)) {
            tvPayStatusTip.setText(getString(R.string.suit_pay_success));
            tvWaitCoinOutTime.setVisibility(View.VISIBLE);
            startCountDownTime(5, tvWaitCoinOutTime, mPayStatusDialog);
            Glide.with(getContext()).load(R.mipmap.icon_logo).into(ivPayStatusImg);
        } else if (status.equals(FustionTag.PAY_STATUS.PAY_FAILED)) {
            Glide.with(getContext()).load(R.mipmap.icon_logo).into(ivPayStatusImg);
            tvPayStatusTip.setText(getString(R.string.suit_pay_failed));
            tvWaitCoinOutTime.setVisibility(View.GONE);
        }

        mPayStatusDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                FusionCode.QrIsLoading = false;
                FusionCode.SCAN_TYPE = FusionCode.CANCEL;
            }
        });
    }

    private void startCountDownTime(final long time, final AppCompatTextView tvWaitCoinOut, final Dialog dialog) {
        timer = new CountDownTimerUtil(time * 1000, 1000) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                tvWaitCoinOut.setText(String.format(getString(R.string.goods_pay_success), String.valueOf(millisUntilFinished / 1000)));
            }

            @Override
            public void onFinish() {
                dialog.dismiss();

            }
        };
        timer.start();// 开始计时
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onQrScanEvent(QrScanEvent event) {
        if (event != null && event.getData() != null) {
            String qrCode = event.getData().getString(FusionString.QR_CODE);
            showShortToast(qrCode);
            qrPay(qrCode, mCurrentBillNo);

        }
    }

    private void qrPay(String qrCode, String billNo) {

        WeakHashMap<String, Object> params = new WeakHashMap<>();
        params.put("deptId", FustionManager.mLoginData.getUser().getUser().getDept().getId());
        params.put("authCode", qrCode);
        params.put("billNo", billNo);
        params.put("description", "");
        params.put("totalFee", "0.1");
        params.put("payBillType", "1");

        HttpHelper.RestClientPost(params, HttpUrl.CODE_PAY,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        if (code == 201) {
                            showShortToast("onSuccess:" + code + "||" + response);
                            FusionCode.QrIsLoading = false;
                            showPayStatusDialog(FustionTag.PAY_STATUS.PAY_SUCCESS);
                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {

                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {

                    }
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
        FusionCode.SCAN_TYPE = FusionCode.CANCEL;
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }
}
